from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
import datetime  # for checking renewal date range.

from django import forms
from .models import Book, Author, Genre, Language, BookInstance, Comment # Import all necessary models

class RenewBookForm(forms.Form):
    """Form for a librarian to renew books."""
    renewal_date = forms.DateField(
            help_text=_("Enter a date between now and 4 weeks (default 3)."))

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['renewal_date'].widget.attrs.update({'class': 'form-control'})

    def clean_renewal_date(self):
        data = self.cleaned_data['renewal_date']

        # Check date is not in past.
        if data < datetime.date.today():
            raise ValidationError(_('Invalid date - renewal in past'))
        # Check date is in range librarian allowed to change (+4 weeks)
        if data > datetime.date.today() + datetime.timedelta(weeks=4):
            raise ValidationError(
                _('Invalid date - renewal more than 4 weeks ahead'))

        # Remember to always return the cleaned data.
        return data


class RatingForm(forms.Form):
    RATING_CHOICES = [(i, str(i)) for i in range(1, 6)] # Choices from 1 to 5
    rating = forms.ChoiceField(
        choices=RATING_CHOICES,
        widget=forms.RadioSelect, # Or forms.Select if you prefer a dropdown
        label=_("Your Rating")
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # For RadioSelect, Bootstrap styling is typically done in the template with form-check classes
        # If using forms.Select, you could add 'form-control' here:
        # if isinstance(self.fields['rating'].widget, forms.Select):
        #     self.fields['rating'].widget.attrs.update({'class': 'form-control'})



class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ['title', 'author', 'summary', 'isbn', 'genre', 'language']
        widgets = {
            'genre': forms.CheckboxSelectMultiple,
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            if not isinstance(field.widget, (forms.CheckboxInput, forms.CheckboxSelectMultiple, forms.RadioSelect)):
                field.widget.attrs.update({'class': 'form-control'})
            # For CheckboxSelectMultiple, Bootstrap 5 styling is more complex and often handled in the template
            # or with a custom widget. Adding 'form-control' to the main widget might not be ideal.
            # However, if it's a standard SelectMultiple (default for ManyToManyField without custom widget):
            elif isinstance(field.widget, forms.SelectMultiple):
                 field.widget.attrs.update({'class': 'form-control'})

            # Specific adjustments
            if field_name == 'genre' and isinstance(field.widget, forms.SelectMultiple):
                field.widget.attrs.update({'size': '5'}) # As seen in the screenshot
            
            if field_name == 'summary':
                field.widget.attrs.update({'rows': '3'})


class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author
        fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']
        widgets = {
            'date_of_birth': forms.DateInput(attrs={'type': 'date'}),
            'date_of_death': forms.DateInput(attrs={'type': 'date'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            if not isinstance(field.widget, (forms.CheckboxInput, forms.RadioSelect)):
                current_class = field.widget.attrs.get('class', '')
                field.widget.attrs.update({'class': f'{current_class} form-control'.strip()})


class GenreForm(forms.ModelForm):
    class Meta:
        model = Genre
        fields = ['name']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].widget.attrs.update({'class': 'form-control'})


class LanguageForm(forms.ModelForm):
    class Meta:
        model = Language
        fields = ['name']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].widget.attrs.update({'class': 'form-control'})


class BookInstanceForm(forms.ModelForm):
    class Meta:
        model = BookInstance
        fields = ['book', 'imprint', 'due_back', 'borrower', 'status']
        widgets = {
            'due_back': forms.DateInput(attrs={'type': 'date'}),
            'status': forms.RadioSelect,
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            if not isinstance(field.widget, (forms.CheckboxInput, forms.RadioSelect)):
                current_class = field.widget.attrs.get('class', '')
                field.widget.attrs.update({'class': f'{current_class} form-control'.strip()})
            if field_name == 'borrower' and isinstance(field.widget, forms.Select):
                 field.widget.attrs.update({'class': 'form-control'})


class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('text',)
        widgets = {
            'text': forms.Textarea(attrs={'rows': 4, 'class': 'form-control'}),
        }
        labels = {
            'text': _('Your Comment'),
        }

